package net.qhzw.vip.qiyu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import net.qhzw.vip.qiyu.dto.DeliveryManDto;
import net.qhzw.vip.qiyu.entity.Area;
import net.qhzw.vip.qiyu.entity.DeliveryMan;
import net.qhzw.vip.qiyu.entity.Shop;
import net.qhzw.vip.qiyu.feign.ShopFeignClient;
import net.qhzw.vip.qiyu.handler.ApiException;
import net.qhzw.vip.qiyu.result.JsonResult;
import net.qhzw.vip.qiyu.service.AdminUserService;
import net.qhzw.vip.qiyu.service.AreaService;
import net.qhzw.vip.qiyu.service.DeliveryManService;
import net.qhzw.vip.qiyu.service.TransportService;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("delivery/man")
@Api(tags = "自提点管理")
public class DeliveryManController {

    @Autowired
    private DeliveryManService deliveryManService;

    @Autowired
    private TransportService transportService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private ShopFeignClient shopFeignClient;


    @Autowired
    private AdminUserService adminUserService;

    @GetMapping("{id}")
    public JsonResult<DeliveryMan> findById(@PathVariable Long id) {
        DeliveryMan deliveryMan = deliveryManService.getById(id);
        //deliveryMan.setRealName(initRealName(deliveryMan.getAreaId()) + deliveryMan.getRealName());
        deliveryMan.setAddre(initRealName(deliveryMan.getAreaId()));
        return JsonResult.ok(deliveryMan);
    }


    /**
     * 初始化自提点地址
     *
     * @param areaId
     * @return
     */
    public String initRealName(Long areaId) {
        String realName = null;
        Area area = areaService.getAreaById(areaId);
        if (area != null && !StringUtils.isEmpty(area.getAddre())) {
            realName = area.getAddre();
        }
        return realName;
    }

    @GetMapping
    public JsonResult<Page<DeliveryMan>> findByPage(Page<DeliveryMan> page, DeliveryMan deliveryMan) {
        Long shopId =  adminUserService.getLoginUser(SecurityUtils.getUserId()).getShopId();
        Shop data = shopFeignClient.findById(shopId).getData();
        if (data == null) {
            throw new ApiException("商户信息有误!");
        }
//        if (0 != data.getShopType() && 5 != data.getShopType()) {
//            throw new ApiException(data.getShopName() + " 该商户没有权限!");
//        }
        if (0 != data.getShopType()) {
            deliveryMan.setShopId(shopId);
        }
        Page<DeliveryMan> deliveryManPage = deliveryManService.page(page, queryWrapper(deliveryMan));
        List<DeliveryMan> records = deliveryManPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (DeliveryMan record : records) {
                record.setAddre(initRealName(record.getAreaId()));
            }
        }
        return JsonResult.ok(deliveryManPage);
    }

    @GetMapping("list")
    public JsonResult<List<DeliveryMan>> list(DeliveryMan deliveryMan) {
        List<DeliveryMan> list = deliveryManService.list(queryWrapper(deliveryMan));
        if (!CollectionUtils.isEmpty(list)) {
            for (DeliveryMan record : list) {
                record.setAddre(initRealName(record.getAreaId()));
            }
        }
        return JsonResult.ok(list);
    }

    @PostMapping
    public JsonResult add(@RequestBody DeliveryMan deliveryMan) {
        //Long shopId = SecurityUtils.getLoginUser().getShopId();
        //deliveryMan.setShopId(shopId);
        boolean isOK = deliveryManService.save(deliveryMan);
        if (isOK)
            return JsonResult.ok();
        return JsonResult.fail();
    }

    @PutMapping
    public JsonResult update(@RequestBody DeliveryMan deliveryMan) {
//        Long shopId = SecurityUtils.getLoginUser().getShopId();
//        deliveryMan.setShopId(shopId);
        boolean isOK = deliveryManService.updateById(deliveryMan);
        if (isOK)
            return JsonResult.ok();
        return JsonResult.fail();
    }

    @DeleteMapping("{id}")
    public JsonResult<DeliveryMan> del(@PathVariable long id) {
        boolean isOK = deliveryManService.removeById(id);
        if (isOK)
            return JsonResult.ok();
        return JsonResult.fail();
    }


    /**
     * 商户绑定自提点
     */
    @PostMapping("bindMerchants")
    public JsonResult bindMerchants(@RequestBody DeliveryMan deliveryMan) {
        boolean isOK = deliveryManService.bindMerchants(deliveryMan);
        if (isOK)
            return JsonResult.ok();
        return JsonResult.fail();
    }


    private LambdaQueryWrapper<DeliveryMan> queryWrapper(DeliveryMan deliveryMan) {
        LambdaQueryWrapper<DeliveryMan> query = new LambdaQueryWrapper<DeliveryMan>()
                .eq(deliveryMan != null && deliveryMan.getShopId() != null, DeliveryMan::getShopId, deliveryMan.getShopId())
                .like(deliveryMan != null && !StringUtils.isEmpty(deliveryMan.getRealName()),
                        DeliveryMan::getRealName,
                        deliveryMan.getRealName())
                .like(deliveryMan != null && !StringUtils.isEmpty(deliveryMan.getMobile()),
                        DeliveryMan::getMobile,
                        deliveryMan.getMobile())
                .like(deliveryMan != null && !StringUtils.isEmpty(deliveryMan.getResponsibleArea()),
                        DeliveryMan::getResponsibleArea,
                        deliveryMan.getResponsibleArea())
                .last("ORDER BY created DESC");
        return query;
    }


    @GetMapping("pickupPoint")
    public JsonResult<List<DeliveryManDto>> pickupPoint(Integer isVip) {
        if (isVip == null) {
            isVip = 0;
        }
        //查询提货点地区
        List<DeliveryManDto> deliveryManDtos = areaService.deliveryPntRgn(isVip);
        List<DeliveryManDto> rootList = null;
        if (!CollectionUtils.isEmpty(deliveryManDtos)) {
            deliveryManDtos = bindDeliveryManArea(deliveryManDtos);
            rootList = new ArrayList<>();
            for (DeliveryManDto deliveryManDto : deliveryManDtos) {
                if (deliveryManDto.getLevel() == 2) {
                    rootList.add(deliveryManDto);
                }
            }

            for (DeliveryManDto deliveryManDto : rootList) {
                deliveryManDto.setChilds(getChild(deliveryManDto.getAreaId(), deliveryManDtos));
            }
        }

        return JsonResult.ok(rootList);

    }

    private List<DeliveryManDto> bindDeliveryManArea(List<DeliveryManDto> deliveryManDtos) {
        List<Long> areaIds = deliveryManDtos.stream().map(DeliveryManDto::getAreaId).collect(Collectors.toList());
        List<DeliveryMan> list = deliveryManService.list(new LambdaQueryWrapper<DeliveryMan>().in(DeliveryMan::getAreaId, areaIds));
        for (DeliveryManDto deliveryManDto : deliveryManDtos) {
            for (DeliveryMan deliveryMan : list) {
                if (deliveryManDto.getAreaId().equals(deliveryMan.getAreaId())){
                    deliveryManDto.setPrice(deliveryMan.getPrice());
                    deliveryManDto.setDeliveryId(deliveryMan.getId());
                    deliveryManDto.setDeliveryName(deliveryMan.getRealName());
                }
            }
        }
        return deliveryManDtos;
    }


    public JsonResult<List<DeliveryManDto>> pickupPoint1(Integer isVip) {
        if (isVip == null) {
            isVip = 0;
        }
        List<DeliveryMan> list = deliveryManService.list(new LambdaQueryWrapper<DeliveryMan>()
                .eq(DeliveryMan::getStatus, 1)
                .eq(DeliveryMan::getIsVip, isVip));
        List<Long> areaIds = list.stream().map(DeliveryMan::getAreaId).distinct().collect(Collectors.toList());
        List<DeliveryManDto> root = null;
        if (areaIds != null) {
            List<DeliveryManDto> deliveryManDtos = deliveryManService.selectDeliveryManDto(areaIds);
            //一级地区
            root = deliveryManDtos.stream().filter(deliveryManDto ->
                    deliveryManDto.getLevel() == 2)
                    .distinct()
                    .collect(Collectors.toList());
            //查询所以的二级菜单
            for (DeliveryManDto rootmenu : root) {
                rootmenu.setChilds(getChild(rootmenu.getAreaId(), deliveryManDtos));
            }
        }
        // List<DeliveryMan> list =  deliveryManService.pickupPoint(isVip);
        return JsonResult.ok(root);
    }

    private List<DeliveryManDto> getChild(Long parentId, List<DeliveryManDto> sources) {
        List<DeliveryManDto> childs = new ArrayList<>();
        for (DeliveryManDto source : sources) {
            if (source.getParentId().equals(parentId)) { // 找儿子
                childs.add(source);
                source.setChilds(getChild(source.getAreaId(), sources)); // 给该儿子设置儿子
            }
        }
        return childs;

    }


}
